# mock_data.py
import numpy as np
import pandas as pd
from datetime import datetime, timedelta


def generate_mock_data(conn, days=30):
    """生成零食相关的模拟数据"""
    cursor = conn.cursor()

    # 添加零食店铺信息
    shops = [
        (1, '美味零食铺', '零食', '2023-03-10'),
        (2, '健康零食工坊', '零食', '2022-09-15')
    ]
    cursor.executemany('INSERT OR IGNORE INTO shops VALUES (?, ?, ?, ?)', shops)

    # 生成日期范围
    dates = [(datetime.now() - timedelta(days=i)).strftime('%Y-%m-%d')
             for i in range(days, 0, -1)]

    # 生成流量总览数据
    traffic_data = []
    for shop_id in [1, 2]:
        for i, date in enumerate(dates):
            base_visitors = np.random.randint(800, 2500) + i * 15
            traffic_data.append((
                shop_id, date, base_visitors,
                int(base_visitors * np.random.uniform(2.8, 4.8)),  # pageviews
                np.random.uniform(0.35, 0.65),  # bounce_rate
                np.random.uniform(0.025, 0.095),  # conversion_rate
                int(base_visitors * np.random.uniform(0.025, 0.085)),  # payment_count
                np.random.uniform(1500, 15000)  # payment_amount
            ))
    cursor.executemany('''
        INSERT INTO traffic_overview 
        (shop_id, date, total_visitors, total_pageviews, bounce_rate, 
         conversion_rate, payment_count, payment_amount)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ''', traffic_data)

    # 流量来源数据
    source_types = ['商品流量', '店铺流量', '搜索流量', '内容流量']
    source_names = {
        '商品流量': ['猜你喜欢', '商品详情页推荐', '购物车推荐'],
        '店铺流量': ['店铺首页', '活动页', '分类页'],
        '搜索流量': ['淘宝搜索', '天猫搜索', '类目搜索'],
        '内容流量': ['淘宝直播', '有好货', '淘宝短视频']
    }

    source_data = []
    for shop_id in [1, 2]:
        for date in dates:
            for source_type in source_types:
                for name in source_names[source_type]:
                    visitors = np.random.randint(100, 1000)
                    source_data.append((
                        shop_id, date, source_type, name, visitors,
                        np.random.uniform(0.015, 0.12),
                        np.random.randint(1, 11)
                    ))
    cursor.executemany('''
        INSERT INTO traffic_sources 
        (shop_id, date, source_type, source_name, visitors, conversion_rate, rank)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ''', source_data)

    # 零食相关关键词数据
    keywords_list = [
        '零食大礼包', '健康零食', '进口零食', '办公室零食', '儿童零食',
        '坚果炒货', '膨化食品', '巧克力', '饼干糕点', '糖果果冻',
        '肉干肉脯', '蜜饯果干', '海味零食', '素食零食', '低卡零食'
    ]
    keyword_data = []
    for shop_id in [1, 2]:
        for date in dates:
            rank = 1
            for kw in np.random.choice(keywords_list, 10, replace=False):
                visitors = np.random.randint(100, 400)
                keyword_data.append((shop_id, date, kw, visitors, rank))
                rank += 1
    cursor.executemany('''
        INSERT INTO keywords 
        (shop_id, date, keyword, visitors, rank)
        VALUES (?, ?, ?, ?, ?)
    ''', keyword_data)

    # 零食商品流量数据
    products = {
        1: [
            ('进口零食大礼包', 'A001'), ('健康坚果混合装', 'A002'), ('手工曲奇饼干', 'A003'),
            ('低卡魔芋爽', 'A004'), ('网红辣条', 'A005'), ('海苔脆片', 'A006'),
            ('黑巧克力礼盒', 'A007'), ('果冻布丁组合', 'A008'), ('牛肉干组合', 'A009'),
            ('蜜饯果干大礼包', 'A010')
        ],
        2: [
            ('儿童零食礼盒', 'B001'), ('办公室零食套餐', 'B002'), ('素食零食组合', 'B003'),
            ('进口巧克力', 'B004'), ('坚果能量棒', 'B005'), ('海味即食小吃', 'B006'),
            ('低糖饼干', 'B007'), ('水果干组合', 'B008'), ('猪肉脯', 'B009'),
            ('爆米花组合', 'B010')
        ]
    }
    product_data = []
    for shop_id in [1, 2]:
        for date in dates:
            rank = 1
            for product, code in products[shop_id]:
                visitors = np.random.randint(150, 600)
                product_data.append((
                    shop_id, date, f"{product} ({code})", visitors,
                    np.random.uniform(0.035, 0.18), rank
                ))
                rank += 1
    cursor.executemany('''
        INSERT INTO product_traffic 
        (shop_id, date, product_name, visitors, conversion_rate, rank)
        VALUES (?, ?, ?, ?, ?, ?)
    ''', product_data)

    # 人群特征数据
    demographics_data = []
    crowd_types = ['进店人群', '商品访问人群', '转化人群']
    genders = ['男', '女']
    age_groups = ['18-24岁', '25-29岁', '30-34岁', '35-39岁', '40-49岁', '50岁以上']
    cities = ['上海', '北京', '广州', '深圳', '杭州', '成都', '武汉', '南京']
    taoqi_values = ['300-400', '401-500', '501-600', '601-700', '701-800', '801-900', '901-1000']

    for shop_id in [1, 2]:
        for date in dates:
            for crowd in crowd_types:
                # 性别分布
                for gender in genders:
                    # 零食店铺女性比例较高
                    if gender == '女':
                        proportion = np.random.uniform(0.55, 0.75)
                    else:
                        proportion = np.random.uniform(0.25, 0.45)
                    demographics_data.append((
                        shop_id, date, crowd, gender, None, None, None, proportion
                    ))

                # 年龄分布
                for age in age_groups:
                    # 零食消费主力在18-34岁
                    if age in ['18-24岁', '25-29岁', '30-34岁']:
                        proportion = np.random.uniform(0.15, 0.3)
                    else:
                        proportion = np.random.uniform(0.05, 0.15)
                    demographics_data.append((
                        shop_id, date, crowd, None, age, None, None, proportion
                    ))

                # 城市分布
                for city in cities:
                    # 一线城市比例较高
                    if city in ['上海', '北京', '广州', '深圳']:
                        proportion = np.random.uniform(0.12, 0.25)
                    else:
                        proportion = np.random.uniform(0.05, 0.12)
                    demographics_data.append((
                        shop_id, date, crowd, None, None, city, None, proportion
                    ))

                # 淘气值分布
                for taoqi in taoqi_values:
                    # 中等淘气值比例较高
                    if taoqi in ['501-600', '601-700', '701-800']:
                        proportion = np.random.uniform(0.2, 0.35)
                    else:
                        proportion = np.random.uniform(0.05, 0.2)
                    demographics_data.append((
                        shop_id, date, crowd, None, None, None, taoqi, proportion
                    ))

    cursor.executemany('''
        INSERT INTO user_demographics 
        (shop_id, date, crowd_type, gender, age_group, city, taoqi_value, proportion)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ''', demographics_data)

    conn.commit()
    print(f"成功生成{len(dates)}天零食店铺数据，包含:")
    print(f"- {len(traffic_data)}条流量总览记录")
    print(f"- {len(source_data)}条流量来源记录")
    print(f"- {len(keyword_data)}条关键词记录")
    print(f"- {len(product_data)}条商品流量记录")
    print(f"- {len(demographics_data)}条人群特征记录")